package com.shop.utils;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class UploadFile {

	/**
	 * 图片上传
	 */
	@RequestMapping("/uploadPic")
	@ResponseBody
	public void uploadPic(@RequestParam(value="file",required=true) MultipartFile file,HttpServletResponse response){
		    //获得文件原名
				String originalFileName=file.getOriginalFilename();	
				String pic_src="";
				PrintWriter out=null;
				if(file!=null&&originalFileName!=null&&originalFileName.length()>0)
				{
					//获得文件扩展名
					String extName=originalFileName.substring(originalFileName.lastIndexOf("."));
					String newFileName=UUID.randomUUID()+extName;
					
					//定义存储图片的物理路径
					String pic_path="D:\\pic";
					File descFile=new File(pic_path,newFileName);
					try {
						//完成文件上传操作
						file.transferTo(descFile);
						pic_src="/"+"pic"+"/"+newFileName;
						out=response.getWriter();
						
					} catch (IllegalStateException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				out.println(pic_src);
				}
}
